# @FileName  :  course.py
# @Time      :  2025/7/28 23:10
# @Author    :  Ayanami
# @info      :  课程相关API接口

from typing import List
from datetime import datetime
from fastapi import APIRouter, HTTPException, Query, Path
from app.schemas.course import (
    CourseCreate,
    CourseUpdate,
    CourseResponse,
    CourseListResponse,
    CourseQuery,
    CourseStatistics,
    SubCourseResponse
)
from app.crud.course import course_crud

router = APIRouter(tags=["课程管理"])


@router.post("/", response_model=CourseResponse, summary="创建课程")
async def create_course(course_data: CourseCreate):
    """创建新课程"""
    try:
        course = await course_crud.create(course_data)
        return course
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建课程失败,{str(e)}")


@router.get("/", response_model=CourseListResponse, summary="获取课程列表")
async def get_courses(
    title: str = Query(None, description="课程名称模糊查询"),
    category: int = Query(None, description="课程类型"),
    is_online: bool = Query(None, description="是否在线课程"),
    is_premium: bool = Query(None, description="是否精品课"),
    enable_checkin: bool = Query(None, description="是否启用签到"),
    teacher_id: int = Query(None, description="讲师ID"),
    agent_id: int = Query(None, description="培训机构ID"),
    parent_course: int = Query(None, description="父课程ID"),
    tags: List[str] = Query(None, description="标签筛选"),
    schedule_start: datetime = Query(None, description="上课时间开始"),
    schedule_end: datetime = Query(None, description="上课时间结束"),
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(10, ge=1, le=1000, description="返回记录数")
):
    """获取课程列表，支持多条件查询和分页"""
    query = CourseQuery(
        title=title,
        category=category,
        is_online=is_online,
        is_premium=is_premium,
        enable_checkin=enable_checkin,
        teacher_id=teacher_id,
        agent_id=agent_id,
        parent_course=parent_course,
        tags=tags,
        schedule_start=schedule_start,
        schedule_end=schedule_end,
        skip=skip,
        limit=limit
    )
    courses, total = await course_crud.get_list(query)
    return CourseListResponse(total=total, items=courses)


@router.get("/statistics", response_model=CourseStatistics, summary="获取课程统计信息")
async def get_course_statistics():
    """获取课程统计信息"""
    stats = await course_crud.get_statistics()
    return CourseStatistics(**stats)


@router.get("/premium", response_model=List[CourseResponse], summary="获取精品课程")
async def get_premium_courses(
    limit: int = Query(10, ge=1, le=50, description="返回记录数")
):
    """获取精品课程列表"""
    courses = await course_crud.get_premium_courses(limit)
    return courses


@router.get("/upcoming", response_model=List[CourseResponse], summary="获取即将开始的课程")
async def get_upcoming_courses(
    limit: int = Query(10, ge=1, le=50, description="返回记录数")
):
    """获取即将开始的课程"""
    courses = await course_crud.get_upcoming_courses(limit)
    return courses


@router.get("/search/{keyword}", response_model=List[CourseResponse], summary="搜索课程")
async def search_courses(
    keyword: str = Path(..., description="搜索关键词"),
    limit: int = Query(10, ge=1, le=50, description="返回记录数")
):
    """搜索课程"""
    courses = await course_crud.search_courses(keyword, limit)
    return courses


@router.get("/category/{category}", response_model=List[CourseResponse], summary="根据分类获取课程")
async def get_courses_by_category(
    category: int = Path(..., description="分类ID")
):
    """根据分类获取课程列表"""
    courses = await course_crud.get_courses_by_category(category)
    return courses


@router.get("/teacher/{teacher_id}", response_model=List[CourseResponse], summary="获取指定教师的课程")
async def get_courses_by_teacher(
    teacher_id: int = Path(..., description="教师ID")
):
    """获取指定教师的课程"""
    courses = await course_crud.get_by_teacher(teacher_id)
    return courses


@router.get("/agent/{agent_id}", response_model=List[CourseResponse], summary="获取指定机构的课程")
async def get_courses_by_agent(
    agent_id: int = Path(..., description="机构ID")
):
    """获取指定机构的课程"""
    courses = await course_crud.get_by_agent(agent_id)
    return courses


@router.get("/{course_id}", response_model=CourseResponse, summary="获取课程详情")
async def get_course(
    course_id: int = Path(..., description="课程ID")
):
    """根据ID获取课程详情"""
    course = await course_crud.get_by_id(course_id)
    if not course:
        raise HTTPException(status_code=404, detail="课程不存在")
    return course


@router.get("/{course_id}/sub-courses", response_model=List[SubCourseResponse], summary="获取子课程")
async def get_sub_courses(
    course_id: int = Path(..., description="父课程ID")
):
    """获取子课程列表"""
    sub_courses = await course_crud.get_sub_courses(course_id)
    return sub_courses


@router.put("/{course_id}", response_model=CourseResponse, summary="更新课程信息")
async def update_course(
    course_data: CourseUpdate,
    course_id: int = Path(..., description="课程ID")
):
    """更新课程信息"""
    try:
        course = await course_crud.update(course_id, course_data)
        if not course:
            raise HTTPException(status_code=404, detail="课程不存在")
        return course
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新课程失败,{str(e)}")


@router.delete("/{course_id}", summary="删除课程")
async def delete_course(
    course_id: int = Path(..., description="课程ID")
):
    """删除课程"""
    success = await course_crud.delete(course_id)
    if not success:
        raise HTTPException(status_code=404, detail="课程不存在")
    return {"message": "删除成功"}


@router.patch("/{course_id}/increment-enrollment", summary="增加报名人数")
async def increment_enrollment_count(
    course_id: int = Path(..., description="课程ID")
):
    """增加课程报名人数"""
    success = await course_crud.increment_enrollment_count(course_id)
    if not success:
        raise HTTPException(status_code=404, detail="课程不存在")
    return {"message": "报名人数已更新"}


@router.patch("/{course_id}/decrement-enrollment", summary="减少报名人数")
async def decrement_enrollment_count(
    course_id: int = Path(..., description="课程ID")
):
    """减少课程报名人数"""
    success = await course_crud.decrement_enrollment_count(course_id)
    if not success:
        raise HTTPException(status_code=404, detail="课程不存在")
    return {"message": "报名人数已更新"}


@router.post("/by-tags", response_model=List[CourseResponse], summary="根据标签获取课程")
async def get_courses_by_tags(tags: List[str]):
    """根据标签获取课程"""
    courses = await course_crud.get_courses_by_tags(tags)
    return courses